package com.keyou.reggie.config;

import com.alibaba.fastjson.JSON;
import com.keyou.reggie.common.BaseContext;
import com.keyou.reggie.common.CommonConstants;
import com.keyou.reggie.common.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: klq
 * @Date: 2023/1/9 19:32
 * @Description:
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    /**
     * AntPathMatcher：基于Ant风格的路径匹配器（Ant风格：用于URL/目录这种标准分段式路径匹配），
     * URL相较于普通的字符串具有很强的规律性：标准的分段式
     */
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的URL
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);

        //定义不需要处理的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/static/**",
                "/common/**",
                "/user/test",
                "/user/login",
                "/user/senMsg"
        };

        //2.判断本次请求是否需要处理
        boolean checkUrl = checkUrl(urls, requestURI);

        //3.如果不需要处理，则直接放行
        if (checkUrl) {
            log.info("本次请求：{}，不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        Long employeeId = (Long) request.getSession().getAttribute(CommonConstants.SESSION_EMPLOYEE);
        //4.1 判断web端登录状态，如果已登录，则直接放行
        if (employeeId != null) {
            log.info("web用户已登录，id为{}", employeeId);
            //在这里获取一下线程id
            long id = Thread.currentThread().getId();
            log.info("doFilter的线程id为：{}", id);

            //使用BaseContext封装id,用于公共字段填充（updateUser、insertUser）
            BaseContext.setCurrentId(employeeId);

            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //4.2 判断移动端用户是否登录
        Long userId = (Long) request.getSession().getAttribute(CommonConstants.SESSION_USER);
        if (userId != null) {
            log.info("移动端用户已登录，用户id为：{}", userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        //5.如果未登录则返回未登录结果,通过输出流方式向客户端页面响应数据
        log.info("用户未登录，id为{}", employeeId);
        response.getWriter().write(JSON.toJSONString(ResultInfo.error(CommonConstants.NOT_LOGIN)));
    }

    private boolean checkUrl(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                //匹配
                return true;
            }
        }
        //不匹配
        return false;
    }
}